package com.shuda.business.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.crm.entity.FollowUpReminderEntity;
import com.shuda.business.crm.mapper.FollowUpReminderMapper;
import com.shuda.business.crm.service.FollowUpReminderService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 跟进提醒Service实现类
 * @author shuda
 */
@Service
@RequiredArgsConstructor
public class FollowUpReminderServiceImpl extends ServiceImpl<FollowUpReminderMapper, FollowUpReminderEntity> 
        implements FollowUpReminderService {

    private static final Logger log = LoggerFactory.getLogger(FollowUpReminderServiceImpl.class);

    private final FollowUpReminderMapper followUpReminderMapper;

    @Override
    public IPage<FollowUpReminderEntity> getFollowUpReminderPage(Page<FollowUpReminderEntity> page, 
                                                             Long userId, 
                                                             Long customerId, 
                                                             String reminderStatus, 
                                                             String reminderType) {
        LambdaQueryWrapper<FollowUpReminderEntity> queryWrapper = new LambdaQueryWrapper<>();
        
        if (userId != null) {
            queryWrapper.eq(FollowUpReminderEntity::getUserId, userId);
        }
        
        if (customerId != null) {
            queryWrapper.eq(FollowUpReminderEntity::getCustomerId, customerId);
        }
        
        if (reminderStatus != null && !reminderStatus.trim().isEmpty()) {
            queryWrapper.eq(FollowUpReminderEntity::getReminderStatus, reminderStatus);
        }
        
        if (reminderType != null && !reminderType.trim().isEmpty()) {
            queryWrapper.eq(FollowUpReminderEntity::getReminderType, reminderType);
        }
        
        queryWrapper.orderByDesc(FollowUpReminderEntity::getReminderTime)
                   .orderByDesc(FollowUpReminderEntity::getCreateTime);
        
        return this.page(page, queryWrapper);
    }

    @Override
    public FollowUpReminderEntity getFollowUpReminderById(Long id) {
        return this.getById(id);
    }

    @Override
    public List<FollowUpReminderEntity> getFollowUpRemindersByCustomerId(Long customerId, String reminderStatus) {
        return followUpReminderMapper.selectByCustomerId(customerId, reminderStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createFollowUpReminder(FollowUpReminderEntity reminderEntity) {
        // 设置默认状态为待提醒
        if (reminderEntity.getReminderStatus() == null) {
            reminderEntity.setReminderStatus("pending");
        }
        
        // 设置默认提醒方式为系统提醒
        if (reminderEntity.getReminderType() == null) {
            reminderEntity.setReminderType("system");
        }
        
        return this.save(reminderEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFollowUpReminder(FollowUpReminderEntity reminderEntity) {
        return this.updateById(reminderEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteFollowUpReminder(Long id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteFollowUpReminder(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public List<FollowUpReminderEntity> getPendingReminders(LocalDateTime currentTime) {
        return followUpReminderMapper.selectPendingReminders(currentTime);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean executeReminder(Long reminderId) {
        FollowUpReminderEntity reminderEntity = this.getById(reminderId);
        if (reminderEntity == null) {
            log.warn("跟进提醒不存在，ID: {}", reminderId);
            return false;
        }
        
        if (!"pending".equals(reminderEntity.getReminderStatus())) {
            log.warn("跟进提醒状态不是待提醒，ID: {}，状态: {}", reminderId, reminderEntity.getReminderStatus());
            return false;
        }
        
        // 执行提醒逻辑（这里可以添加具体的提醒实现，如发送邮件、短信等）
        log.info("执行跟进提醒，客户ID: {}，用户ID: {}，提醒内容: {}", 
                reminderEntity.getCustomerId(), reminderEntity.getUserId(), reminderEntity.getReminderContent());
        
        // 更新提醒状态
        LocalDateTime now = LocalDateTime.now();
        int updatedRows = followUpReminderMapper.updateReminderStatus(reminderId, "reminded", now);
        
        return updatedRows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchExecuteReminder(Long[] reminderIds) {
        boolean allSuccess = true;
        for (Long reminderId : reminderIds) {
            boolean success = executeReminder(reminderId);
            if (!success) {
                allSuccess = false;
            }
        }
        return allSuccess;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelReminder(Long reminderId) {
        FollowUpReminderEntity reminderEntity = this.getById(reminderId);
        if (reminderEntity == null) {
            log.warn("跟进提醒不存在，ID: {}", reminderId);
            return false;
        }
        
        if (!"pending".equals(reminderEntity.getReminderStatus())) {
            log.warn("跟进提醒状态不是待提醒，ID: {}，状态: {}", reminderId, reminderEntity.getReminderStatus());
            return false;
        }
        
        // 更新提醒状态为已取消
        int updatedRows = followUpReminderMapper.updateReminderStatus(reminderId, "cancelled", null);
        
        return updatedRows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCancelReminder(Long[] reminderIds) {
        boolean allSuccess = true;
        for (Long reminderId : reminderIds) {
            boolean success = cancelReminder(reminderId);
            if (!success) {
                allSuccess = false;
            }
        }
        return allSuccess;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processPendingReminders() {
        LocalDateTime currentTime = LocalDateTime.now();
        List<FollowUpReminderEntity> pendingReminders = getPendingReminders(currentTime);
        
        int processedCount = 0;
        for (FollowUpReminderEntity reminder : pendingReminders) {
            boolean success = executeReminder(reminder.getId());
            if (success) {
                processedCount++;
            }
        }
        
        log.info("处理待提醒的跟进提醒，共处理 {} 条记录", processedCount);
        return processedCount;
    }
}